package com.yumeng.framework.auth.security.configurers;

import com.yumeng.framework.auth.security.authentication.sms.SmsAuthenticationProvider;
import com.yumeng.framework.auth.security.authentication.sms.SmsLoginAuthenticationFilter;
import com.yumeng.framework.auth.security.userdetails.SmsUserDetailsServiceImpl;
import com.yumeng.framework.auth.service.auth.SmsAuthService;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 短信登录配置
 *
 * @author wxd
 * @date 2025/4/11 19:42
 */
public final class SmsLoginConfigurer<H extends HttpSecurityBuilder<H>> extends
        MyAbstractAuthenticationFilterConfigurer<H, SmsLoginConfigurer<H>, SmsLoginAuthenticationFilter> {

    private final SmsLoginAuthenticationFilter filter;
    private final SmsAuthService smsAuthService;

    protected SmsLoginConfigurer(SmsLoginAuthenticationFilter filter, SmsAuthService smsAuthService) {
        super(filter, null);
        this.filter = filter;
        this.smsAuthService = smsAuthService;
        phoneParameter("phone");
        smsCodeParameter("smsCode");
        clientTypeParameter("clientType");
    }

    @Override
    public SmsLoginConfigurer<H> loginPage(String loginPage) {
        return super.loginPage(loginPage);
    }

    @Override
    protected AuthenticationProvider customAuthenticationProvider() {
        SmsUserDetailsServiceImpl detailsService = new SmsUserDetailsServiceImpl(smsAuthService);
        AuthenticationProvider provider = new SmsAuthenticationProvider(detailsService);
        return provider;
    }

    public SmsLoginConfigurer<H> phoneParameter(String phoneParameter) {
        getAuthenticationFilter().setPhoneParameter(phoneParameter);
        return this;
    }

    public SmsLoginConfigurer<H> smsCodeParameter(String smsCodeParameter) {
        getAuthenticationFilter().setSmsCodeParameter(smsCodeParameter);
        return this;
    }

    @Override
    public void init(H http) throws Exception {
        super.init(http);
    }

    @Override
    protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
        return PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, loginProcessingUrl);
    }

    public static SmsLoginConfigurer<HttpSecurity> smsLogin(SmsAuthService smsAuthService){
        SmsLoginAuthenticationFilter filter = new SmsLoginAuthenticationFilter();
        return new SmsLoginConfigurer<>(filter, smsAuthService);
    }
}
